﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Base;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.ServiceProvider;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    /// <summary>
    /// 服务商管理
    /// </summary>
    public class ServiceProviderController : BaseController
    {

        #region 服务商管理

        #region 服务商列表 +  ActionResult ServiceProviderIndex()
        public ActionResult ServiceProviderIndex()
        {
            return View();
        }
        #endregion

        #region 服务商管理页面获取列表数据 + ActionResult ServiceProviderList(ServiceProviderModel model)
        /// <summary>
        /// 服务商管理页面获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceProviderList(ServiceProviderModel model)
        {
            var total = 0;
            var list = ServiceFactory.ServiceProviderServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.ServiceProviderName,
                ServiceProviderTypeList = o.ServiceProviderType.Select(t => new { ServiceProviderTypeName = EnumHelper.Instance.GetDescription(typeof(ServiceProductType), t.ServiceProviderTypeCode) }),
                o.ContactPhone,
                o.ContactEmail,
                o.IsAvailable,
                o.BankAccountName,
                o.BankAccount,
                o.BankName,
                o.LastModifyBy,
                o.ServiceCode
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 服务商编辑 + ActionResult ServiceProviderEdit(int id)
        /// <summary>
        /// 服务商编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceProviderEdit(int id)
        {
            ViewBag.ShowTitle = id > 0 ? "编辑配件类型" : "添加配件类型";
            var accessoriesType = ServiceFactory.ServiceProviderServiceInstance.LoadByID(id);
            return View(accessoriesType);
        }

        #endregion

        #region 保存服务商 + ActionResult SaveServiceProvider(ServiceProvider model)
        [HttpPost]
        [ValidateInput(false)]
        //保存服务商
        public ActionResult SaveServiceProvider(ServiceProvider model, List<byte> ServiceProviderType)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            var serv = ServiceFactory.ServiceProviderServiceInstance;
            model.ServiceProviderName = model.ServiceProviderName.Trim();
            if (model.ID == 0)
            {
                if (serv.IsExist(model.ServiceProviderName))
                {
                    responseResult.Message = "该服务商已经存在";
                }
                else
                {
                    model.CreateTime = DateTime.Now;
                    model.CreateBy = CurrentUser.UserAccount;
                    model.LastModifyBy = CurrentUser.UserAccount;
                    model.LastModifyTime = DateTime.Now;

                    using (TransactionScope ts = new TransactionScope())
                    {
                        var entity = serv.AddEntities(model);
                        responseResult.Success = entity.ID > 0;
                        bool tag = false;//标记事务对象是否被释放
                        if (responseResult.Success)
                        {
                            //设置服务商编码
                            entity.ServiceCode = CommonMethod.GenerateCode("FWS", entity.ID.ToString(), 6);
                            if (!serv.UpdateEntities(entity))
                            {
                                LogHelper.WriteLog("设置服务商编码失败：" + entity.ID, LogType.remark);
                                tag = true;
                                ts.Dispose();
                            }

                            if (responseResult.Success && ServiceProviderType != null)
                            {
                                var serviceType = ServiceFactory.ServiceProviderTypeServiceInstance;
                                ServiceProviderType item = new ServiceProviderType();
                                //添加服务商类型
                                foreach (byte type in ServiceProviderType)
                                {
                                    item.ServiceProviderID = entity.ID;
                                    item.ServiceProviderTypeCode = type;
                                    var re = serviceType.AddEntities(item);
                                    if (re.ID < 1)
                                    {
                                        LogHelper.WriteLog("新增服务商类型失败：" + JsonConvert.SerializeObject(item), LogType.remark);
                                        tag = true;
                                        ts.Dispose();
                                        break;
                                    }
                                }
                            }
                        }
                        if (!tag)
                            ts.Complete();

                    }
                }
            }
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity != null)
                {
                    if (entity.ServiceProviderName != model.ServiceProviderName && serv.IsExist(model.ServiceProviderName, model.ID))
                    {
                        responseResult.Message = "已存在同名的服务商，请修改服务商名称";
                    }
                    else
                    {
                        entity.IsAvailable = model.IsAvailable;
                        entity.ServiceProviderName = model.ServiceProviderName;
                        entity.BankAccount = model.BankAccount;
                        entity.BankAccountName = model.BankAccountName;
                        entity.BankName = model.BankName;
                        entity.ContactEmail = model.ContactEmail;
                        entity.ContactPhone = model.ContactPhone;
                        entity.LastModifyBy = CurrentUser.UserAccount;
                        entity.LastModifyTime = DateTime.Now;
                        using (TransactionScope ts = new TransactionScope())
                        {
                            responseResult.Success = ServiceFactory.ServiceProviderServiceInstance.UpdateEntities(entity);
                            bool tag = false; //标记事务对象是否被释放
                            if (responseResult.Success)
                            {
                                var serviceType = ServiceFactory.ServiceProviderTypeServiceInstance;
                                //1、删除现有的服务商类型
                                bool deleteReslut = serviceType.DeleteServiceProviderType(model.ID);
                                if (ServiceProviderType != null)
                                {
                                    ServiceProviderType item = new ServiceProviderType();
                                    //添加服务商类型
                                    foreach (byte type in ServiceProviderType)
                                    {
                                        item.ServiceProviderID = entity.ID;
                                        item.ServiceProviderTypeCode = type;
                                        var re = serviceType.AddEntities(item);
                                        if (re.ID < 1)
                                        {
                                            LogHelper.WriteLog("新增服务商类型失败：" + JsonConvert.SerializeObject(item), LogType.remark);
                                            tag = true;
                                            ts.Dispose();
                                            break;
                                        }
                                    }
                                }
                            }
                            if (!tag)
                                ts.Complete();
                        }
                    }
                }
                else
                {
                    responseResult.Message = "该服务商不存在或已被删除";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("ServiceProviderIndex");
        }


        #endregion

        #region 禁用/启用服务商 + JsonResult ServiceProviderUpdateStatus(int id, bool isAvailable)
        /// <summary>
        /// 禁用/启用服务商
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="isAvailable">启用/禁用</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ServiceProviderUpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.ServiceProviderServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {

                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.ServiceProviderServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #endregion

        #region 服务商网点管理

        #region 服务商网点列表 +  ActionResult ServiceProviderBranchIndex()
        public ActionResult ServiceProviderBranchIndex()
        {
            return View();
        }
        #endregion

        #region 服务商网点管理页面获取列表数据 + ActionResult ServiceProviderBranchList(ServiceProviderBranchModel model)
        /// <summary>
        /// 服务商网点管理页面获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceProviderBranchList(ServiceProviderBranchModel model)
        {
            var total = 0;
            var list = ServiceFactory.ServiceProviderBranchServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                // TypeName = o.ServiceProvider.ServiceProviderType.TypeName,
                ServiceProviderName = o.ServiceProvider.ServiceProviderName,
                //BranchTypeName = o.ServiceProviderBranchType.BranchTypeName,
                o.BranchName,
                ProvinceName = o.D_Province.ProvinceName,
                CityName = o.D_City.CityName,
                o.ContactName,
                o.ContactPhone,
                o.BranchCode,
                o.ContactEmail,
                o.IsAvailable,
                o.LastModifyBy,
                ServiceTypeList = o.ServiceProviderBranchServiceType.Select(t => new { ServiceTypeName = EnumHelper.Instance.GetDescription(typeof(InsuranceWarrantyMaintenanceType), t.ServiceType) })
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 服务商网点编辑 + ActionResult ServiceProviderBranchEdit(int id)
        /// <summary>
        /// 服务商网点编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceProviderBranchEdit(int id)
        {
            ViewBag.ShowTitle = id > 0 ? "编辑配件类型" : "添加配件类型";
            var accessoriesType = ServiceFactory.ServiceProviderBranchServiceInstance.LoadByID(id);
            return View(accessoriesType);
        }

        #endregion

        #region 保存服务商网点 + ActionResult SaveServiceProviderBranch(ServiceProviderBranch model)
        [HttpPost]
        [ValidateInput(false)]
        //保存服务商网点
        public ActionResult SaveServiceProviderBranch(ServiceProviderBranch model, string ServiceTypeList)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            List<ServiceTypeList> ServiceType = null;
            try
            {
                ServiceType = JsonConvert.DeserializeObject<List<ServiceTypeList>>(ServiceTypeList);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("反序列化网点服务类型信息异常" + ex.ToString(), LogType.error);
                responseResult.Message = "操作失败";
                TempData["ResponseResult"] = responseResult;
                return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
            }


            var serv = ServiceFactory.ServiceProviderBranchServiceInstance;
            model.BranchName = model.BranchName.Trim();
            if (model.ID == 0)
            {
                if (serv.IsExist(model.BranchName))
                {
                    responseResult.Message = "该服务商网点已经存在";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                }
                //新增
                model.CreateTime = DateTime.Now;
                model.CreateBy = CurrentUser.UserAccount;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;
                using (TransactionScope ts = new TransactionScope())
                {
                    var entity = serv.AddEntities(model);
                    responseResult.Success = entity.ID > 0;
                    if (!responseResult.Success)
                    {
                        ts.Dispose();
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                    }
                    //设置网点编码
                    model.BranchCode = CommonMethod.GenerateCode("FWSWD", entity.ID.ToString(), 6);
                    bool reCode = serv.UpdateEntities(model);
                    if (!reCode)
                    {
                        ts.Dispose();
                        responseResult.Message = "添加失败，网点编码设置失败";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                    }
                    //添加服务商网点服务类型
                    if (ServiceType != null)
                    {
                        var serviceType = ServiceFactory.ServiceProviderBranchServiceTypeServiceInstance;
                        ServiceProviderBranchServiceType item = new ServiceProviderBranchServiceType();
                        item.ServiceProviderBranchID = entity.ID;
                        foreach (ServiceTypeList type in ServiceType)
                        {
                            item.ServiceProviderTypeID = type.ServiceProviderTypeId;
                            foreach (byte temp in type.ServiceType)
                            {
                                item.ServiceType = temp;
                                var re = serviceType.AddEntities(item);
                                if (re.ID < 1)
                                {
                                    ts.Dispose();
                                    LogHelper.WriteLog("新增服务商网点服务类型失败：" + JsonConvert.SerializeObject(item), LogType.remark);
                                    responseResult.Message = "添加失败，服务类型设置失败";
                                    TempData["ResponseResult"] = responseResult;
                                    return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                                }
                            }

                        }
                    }

                    ts.Complete();
                }
            }
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity == null)
                {
                    responseResult.Message = "该服务商网点不存在或已被删除";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                }

                if (entity.BranchName != model.BranchName && serv.IsExist(model.BranchName, model.ID))
                {
                    responseResult.Message = "已存在同名的服务商网点，请修改服务商网点名称";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                }
                entity.Address = model.Address;
                entity.BranchName = model.BranchName;
                entity.Remark = model.Remark;
                entity.CityId = model.CityId;
                entity.ContactEmail = model.ContactEmail;
                entity.ContactName = model.ContactName;
                entity.ContactPhone = model.ContactPhone;
                entity.IsAvailable = model.IsAvailable;
                entity.ServiceProviderId = model.ServiceProviderId;
                entity.ProvinceId = model.ProvinceId;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                using (TransactionScope ts = new TransactionScope())
                {
                    //修改
                    responseResult.Success = ServiceFactory.ServiceProviderBranchServiceInstance.UpdateEntities(entity);
                    if (!responseResult.Success)
                    {
                        ts.Dispose();
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                    }
                    var serviceType = ServiceFactory.ServiceProviderBranchServiceTypeServiceInstance;
                    //1、删除现有的服务商网点服务类型
                    bool deleteReslut = serviceType.DeleteServiceProviderBranchServiceType(model.ID);
                    if (ServiceType != null)
                    {
                        ServiceProviderBranchServiceType item = new ServiceProviderBranchServiceType();
                        item.ServiceProviderBranchID = entity.ID;
                        foreach (ServiceTypeList type in ServiceType)
                        {
                            item.ServiceProviderTypeID = type.ServiceProviderTypeId;
                            foreach (byte temp in type.ServiceType)
                            {
                                item.ServiceType = temp;
                                var re = serviceType.AddEntities(item);
                                if (re.ID < 1)
                                {
                                    ts.Dispose();
                                    LogHelper.WriteLog("新增服务商网点服务类型失败：" + JsonConvert.SerializeObject(item), LogType.remark);
                                    responseResult.Message = "修改失败，服务类型设置失败";
                                    TempData["ResponseResult"] = responseResult;
                                    return RedirectToAction("ServiceProviderBranchEdit", new { id = model.ID });
                                }
                            }
                        }
                    }
                    ts.Complete();
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("ServiceProviderBranchIndex");
        }

        #endregion

        #region 禁用/启用服务商网点 + JsonResult ServiceProviderBranchUpdateStatus(int id, bool isAvailable)
        /// <summary>
        /// 禁用/启用服务商网点
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="isAvailable">启用/禁用</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ServiceProviderBranchUpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.ServiceProviderBranchServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {

                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.ServiceProviderBranchServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #region 获取服务商的类别列表 + JsonResult GetServiceProviderTypeList(int serviceProviderId)
        /// <summary>
        /// 获取服务商的类别列表
        /// </summary>
        /// <param name="serviceProviderId">服务商ID</param>
        /// <returns></returns>
        public JsonResult GetServiceProviderTypeList(int serviceProviderId)
        {
            var result = ServiceFactory.ServiceProviderTypeServiceInstance.LoadEntities(t => t.ServiceProviderID == serviceProviderId).AsNoTracking().ToList()
                 .Select(t => new
                 {
                     Text = EnumHelper.Instance.GetDescription(typeof(ServiceProductType), t.ServiceProviderTypeCode),
                     Value = t.ID,
                     BranchTypeList = ConvertToSelector.Instance.EnumTypeConvertToSelectList(typeof(InsuranceWarrantyMaintenanceType), 0, false)
                 });
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取已选择的服务类型 + JsonResult GetServiceTypeList(int branchId)
        public JsonResult GetServiceTypeList(int branchId)
        {
            if (branchId < 1)
                return Json("",JsonRequestBehavior.AllowGet);

           var data=  ServiceFactory.ServiceProviderBranchServiceTypeServiceInstance.LoadEntities(t => t.ServiceProviderBranchID == branchId).AsNoTracking()
                .Select(t => new
                {
                  ProductProviderTypeID = t.ServiceProviderTypeID,
                    t.ServiceType
                }).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #endregion
    }
}